from django.conf import settings
from django.db.models import Q
from rest_framework.filters import BaseFilterBackend


class PostsFilterBackend(BaseFilterBackend):  # BaseFilterBackend的子类必须实现filter_queryset()方法
    """
        数据过滤器
    """

    def filter_queryset(self, request, queryset, view):
        """
        过来源数据
        :param request:
        :param queryset:
        :param view:
        :return:
        """
        category_id = int(request.query_params.get('category', 0))  # 获取get参数值
        kw = request.query_params.get('kw', '')
        if category_id:
            queryset = queryset.filter(category_id=int(category_id)).distinct()
        if kw:
            queryset = queryset.filter(
                Q(title__contains=kw) | Q(desc__contains=kw)).distinct()
        return queryset


class RecommendPostsFilterBackend(BaseFilterBackend):

    def filter_queryset(self, request, queryset, view):
        """
        过来源数据
        :param request:
        :param queryset:
        :param view:
        :return:
        """
        return queryset.filter(is_recom=True).distinct()[0:settings.RECOMMEND_LIMIT]
